package org.summer.generator.handler;

import org.summer.generator.config.DatabaseConfig;
import org.summer.generator.log.Logger;
import org.summer.generator.log.LoggerManager;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DefaultDatabaseHandler implements DatabaseHandler {
    private static final Logger log = LoggerManager.getLogger(DefaultDatabaseHandler.class);
    private DatabaseConfig config;
    private Connection connection;

    @Override
    public void connect() {
        try {
            log.debug("加载数据库驱动");
            Class.forName(config.getDriverClassName());
        } catch (ClassNotFoundException e) {
            log.error("数据库驱动加载失败,没有找到驱动类",e);
            throw new RuntimeException(e);
        }
        String url = "jdbc:mysql://%s:%s/%s?serverZoneId=Asia/Shanghai"
                .formatted(config.getHost(),config.getPort(),config.getDatabaseName());
        try {
            log.debug("获取数据库链接对象");
            this.connection = DriverManager.getConnection(url, config.getUsername(), config.getPassword());
        } catch (SQLException e) {
            log.error("获取数据链接出错",e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Connection getConnection() {
        if (this.connection == null){
            log.error("数据库链接对象为空");
            throw new RuntimeException("数据库链接对象为空");
        }
        return this.connection;
    }

    @Override
    public void setConfig(DatabaseConfig config) {
        this.config = config;
    }

    @Override
    public void close() {
        try {
            log.debug("关闭数据库链接");
            this.connection.close();
        } catch (SQLException e) {
            log.error("关闭数据库链接出错");
            throw new RuntimeException(e);
        }
    }
}
